package one.bugu.android.demon.ui.activity.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.snatch.WalletBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.CalculationActivity;
import one.bugu.android.demon.ui.adapter.snatch.MyWalletAdapter;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.ScreenUtils;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * Description MyWalletActivity 我的钱包首页
 *
 * @author liuxin
 * @date 2018/10/27 9:48
 */
@LKContentView(R.layout.activity_my_wallet)
public class MyWalletActivity extends MyBaseActivity {
    /**
     * topbar
     */
    @LKInjectView(R.id.btbv_my_wallet)
    private BaseTopBarView btbv_my_wallet;
    /**
     * 钱包总数
     */
    @LKInjectView(R.id.tv_wallet_num)
    private TextView tv_wallet_num;
    /**
     * 列表数据
     */
    @LKInjectView(R.id.lv_my_wallet)
    private ListView lv_my_wallet;
    /**
     * 列表适配器
     */
    private MyWalletAdapter mAdapter;

    private String token;

    private double BGTCount = 0;

    private double ETHCOUNT = 0;

    private DecimalFormat format = new DecimalFormat("###.##");

    @Override
    protected void initView() {
        super.initView();
        //设置状态栏显示
        StatusBarUtils.getInstance().setStatusBar(this, btbv_my_wallet);

        mAdapter = new MyWalletAdapter(this, null);
        lv_my_wallet.setAdapter(mAdapter);
        //设置默认总资产
        setMyWalletNum(0.0);
    }

    @Override
    protected void initData() {
        super.initData();
        token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);

        getWalletData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        /**
         * topbar事件处理
         */
        btbv_my_wallet.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {

            }
        });
        //列表条目点击事件处理
        lv_my_wallet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<WalletBean> walletBeans = mAdapter.allData();
                if (walletBeans == null) {
                    return;
                }
                WalletBean walletBean = walletBeans.get(position);
                switch (walletBean.getWallteType()) {
                    case 30:
                        //BGT明细页面
                        Intent intent1 = new Intent(MyWalletActivity.this, BGTActivity.class);
                        intent1.putExtra(Constant.NUMBER, walletBean);
                        intent1.putExtra(Constant.PAGETITLE, "我的BGT");
                        startActivityForResult(intent1, 1001);
                        break;
                    case 40:
                        //算力明细
                        Intent intent2 = new Intent(MyWalletActivity.this, CalculationActivity.class);
                        intent2.putExtra(Constant.CALCULATION, String.valueOf(walletBean.getBalance()));
                        startActivity(intent2);
                        break;
                    case 50:
                        //ETH明细页面
                        Intent intent = new Intent(MyWalletActivity.this, BGTActivity.class);
                        intent.putExtra(Constant.NUMBER, walletBean);
                        intent.putExtra(Constant.PAGETITLE, "我的ETH");
                        startActivityForResult(intent, 1001);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1001) {
            //刷新钱包数据
            getWalletData();
        }
    }

    /**
     * 设置钱包总资产
     *
     * @param count 资产数目
     */
    private void setMyWalletNum(double count) {
        String format = this.format.format(count);
        String text = "¥" + format;
        SpannableString walletNum = MyTextUtils.getInstance().setAutoTextSize(text, 0, 1, ScreenUtils.spToPx(this, 23));
        tv_wallet_num.setText(walletNum.toString());
    }

    /**
     * 获取钱包数据
     */
    private void getWalletData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        LKUtil.getHttpManager().postBody(HttpConstant.GET_USER_WALLET, map, getSnatchPeriodHander);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getSnatchPeriodHander =
            new BaseHttpAsycResponceHandler<List<WalletBean>>() {
                @Override
                public void onSuccess(List<WalletBean> walletBeans) {
                    super.onSuccess(walletBeans);
                    if (walletBeans != null) {
                        for (int i = 0; i < walletBeans.size(); i++) {
                            if (walletBeans.get(i).getWallteType() == 40) {
                                walletBeans.remove(i);
                                break;
                            }
                        }
                    }
                    mAdapter.clear();
                    mAdapter.addAll((ArrayList<WalletBean>) walletBeans);

                    getWalletBGTExchange();
                    getWalletETHExchange();
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);

                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

    /**
     * BGT兑换比例
     */
    private void getWalletBGTExchange() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("key", "BGT_TO_RMB");
        LKUtil.getHttpManager().postBody(HttpConstant.WALLET_CONFIG, map, mHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler mHandler =
            new BaseHttpAsycResponceHandler<String>() {
                @Override
                public void onSuccess(String walletBeans) {
                    super.onSuccess(walletBeans);
                    if (TextUtils.isEmpty(walletBeans)) {
                        return;
                    }
                    try {
                        ArrayList<WalletBean> beans = mAdapter.allData();
                        for (int i = 0; i < beans.size(); i++) {
                            if (beans.get(i).getWallteType() == 30) {
                                double bgtPrice = Double.parseDouble(walletBeans);
                                beans.get(i).setPrice(bgtPrice);
                                BGTCount = beans.get(i).getBalance() * bgtPrice;
                                setMyWalletNum(BGTCount + ETHCOUNT);
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);

                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

    /**
     * ETH兑换比例
     */
    private void getWalletETHExchange() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("key", "ETH_TO_RMB");
        LKUtil.getHttpManager().postBody(HttpConstant.WALLET_CONFIG, map, mEthHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler mEthHandler =
            new BaseHttpAsycResponceHandler<String>() {
                @Override
                public void onSuccess(String walletBeans) {
                    super.onSuccess(walletBeans);
                    if (TextUtils.isEmpty(walletBeans)) {
                        return;
                    }
                    try {
                        ArrayList<WalletBean> beans = mAdapter.allData();
                        for (int i = 0; i < beans.size(); i++) {
                            if (beans.get(i).getWallteType() == 50) {
                                double ethPrice = Double.parseDouble(walletBeans);
                                beans.get(i).setPrice(ethPrice);
                                ETHCOUNT = beans.get(i).getBalance() * ethPrice;
                                setMyWalletNum(BGTCount + ETHCOUNT);
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);

                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

}
